package com.example.demo.serviceimpl;

import com.example.demo.entity.StudentEntity;
import com.example.demo.repository.StudentRepository;
import com.example.demo.service.StudentService;
import com.example.demo.util.BatchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xzy
 * @date 2020-11-03 09:38
 * 说明：
 */
@Slf4j
@Service
public class StudentServiceImpl implements StudentService {

    private final StudentRepository studentRepository;
    private final BatchService batchService;

    @Autowired
    public StudentServiceImpl(StudentRepository studentRepository, BatchService batchService) {
        this.studentRepository = studentRepository;
        this.batchService = batchService;
    }

    /**
     * 测试执行批量新增的效率
     */
    @Override
    public void batchSaveTest() {
        List<StudentEntity> studentEntityList = new ArrayList<>(100);
        for (int i = 0; i < 100; i++) {
            StudentEntity studentEntity = new StudentEntity();
            studentEntity.setDeleteFlag("0");
            studentEntityList.add(studentEntity);
        }

        // JPA.saveAll
        long startTime = System.currentTimeMillis();
        studentRepository.saveAll(studentEntityList);
        long endTime = System.currentTimeMillis();
        System.out.println("time1:" + (endTime - startTime));


        List<StudentEntity> studentEntityList2 = new ArrayList<>(100);
        for (int i = 0; i < 100; i++) {
            StudentEntity studentEntity = new StudentEntity();
            studentEntity.setDeleteFlag("0");
            studentEntityList2.add(studentEntity);
        }

        // EntityManager
        startTime = System.currentTimeMillis();
        batchService.batchInsert(studentEntityList2);
        endTime = System.currentTimeMillis();
        System.out.println("time2:" + (endTime - startTime));
    }

    /**
     * 测试事务传播特新
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transactionPropagationTest() {

        StudentEntity studentEntity = new StudentEntity();
        studentEntity.setStudentName("事务测试");
        log.info("插入数据：{}", studentEntity);

        // 运行时异常
        throwAException();

        // 检查回滚是否成功
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
    public void throwAException() {
        throw new RuntimeException();
    }
}
